package com.atguigu.gulimall.auth.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVO;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.service.ILoginService;
import com.atguigu.gulimall.auth.vo.UserLoginVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/9 21:41 周一
 * @description :
 */
@Service
@AllArgsConstructor
public class LoginServiceImpl implements ILoginService {

    private final MemberFeignService memberFeignService;

    @Override
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session) {
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberResponseVO data = login.getData(new TypeReference<MemberResponseVO>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        }
        Map<String, String> errors = new HashMap<>(3);
        errors.put("msg", Objects.toString(login.get("msg")));
        redirectAttributes.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/login.html";
    }

}
